<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="串口号" prop="serialCode">
        <el-input v-model="queryParams.serialCode" placeholder="请输入串口号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['device:serial:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['device:serial:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['device:serial:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['device:serial:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据标识" align="center" prop="id" v-if="false" />
      <el-table-column label="串口号" align="center" prop="serialCode" />
      <el-table-column label="波特率" align="center" prop="baudRate" />
      <el-table-column label="数据位" align="center" prop="dataBit" />
      <el-table-column label="停止位" align="center" prop="stopBit" />
      <el-table-column label="校验位" align="center" prop="checkoutBit" />
      <el-table-column label="采集状态" align="center" prop="gatherType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gather_status" :value="scope.row.gatherType" />
        </template>
      </el-table-column>
      <el-table-column label="设备类别" align="center" prop="deviceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gather_device_type" :value="scope.row.deviceType" />
        </template>
        </el-table-column>
      <el-table-column label="采集时间" align="center" prop="gatherTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['device:serial:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['device:serial:remove']">删除</el-button>
          <el-button v-if="scope.row.gatherType === '1'" size="mini" type="text" icon="el-icon-video-play"
            @click="handleStatus(scope.row, '0')" v-hasPermi="['device:serial:cjkg']">开启采集</el-button>
          <el-button v-if="scope.row.gatherType === '0'" size="mini" type="text" icon="el-icon-video-pause"
            @click="handleStatus(scope.row, '1')" v-hasPermi="['device:serial:cjkg']">关闭采集</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleAuthCommand(scope.row)"
            v-hasPermi="['device:serial:xfml']">命令下发</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleAuthDataCheck(scope.row)"
            v-hasPermi="['serialCheckRef:edit']">分配校验</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改串口对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="串口号" prop="serialCode">
          <el-input v-model="form.serialCode" placeholder="请输入串口号" />
        </el-form-item>
        <el-form-item label="波特率" prop="baudRate">
          <el-input-number v-model="form.baudRate" placeholder="请输入波特率" :min="0" />
        </el-form-item>
        <el-form-item label="数据位" prop="dataBit">
          <el-input-number v-model="form.dataBit" placeholder="请输入数据位" :min="0" />
        </el-form-item>
        <el-form-item label="停止位" prop="stopBit">
          <el-input-number v-model="form.stopBit" placeholder="请输入停止位" :min="0" />
        </el-form-item>
        <el-form-item label="校验位" prop="checkoutBit">
          <el-input-number v-model="form.checkoutBit" placeholder="请输入校验位" :min="0" />
        </el-form-item>
        <el-form-item label="采集时间" prop="gatherTime">
          <el-input v-model="form.gatherTime" placeholder class="inp" />
          <el-button type="primary" @click="showDialog">生成 cron</el-button>
          <el-dialog title="生成 cron" :visible.sync="showCron" :append-to-body="zflag">
            <vcrontab @hide="showCron = false" @fill="crontabFill" :expression="expression"></vcrontab>
          </el-dialog>
        </el-form-item>
        <el-form-item label="设备类别" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择设备类别">
                <el-option v-for="dict in dict.type.gather_device_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import vcrontab from "vcrontab";
import { listSerial, getSerial, delSerial, addSerial, updateSerial, editGather } from "@/api/device/serial";
var ws = null;
export default {
  name: "Serial",
  dicts: ['sys_normal_disable', 'gather_status','gather_device_type'],
  components: { vcrontab },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 串口表格数据
      serialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      fflag: false,
      zflag: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialCode: null,
      },
      // 表单参数
      form: {
        gatherTime:""
      },
      // 表单校验
      rules: {
      },
      expression: "",
      showCron: false,
      wsUrl:""
    };
  },
  created() {
    this.wsUrl = process.env.VUE_APP_WS_URL
    this.getList();
  },
  methods: {
    /** 查询串口列表 */
    getList() {
      this.loading = true;
      listSerial(this.queryParams).then(response => {
        this.serialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialCode: null,
        baudRate: null,
        dataBit: null,
        stopBit: null,
        checkoutBit: null,
        gatherTime: null,
        status: "0",
        remark: null,
        deviceType:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加串口";
    },
    crontabFill(value) {
      //确定后回传的值
      this.form.gatherTime = value;
    },
    showDialog() {
      this.zflag = true;
      this.fflag = true;
      this.expression = this.form.gatherTime;//传入的 cron 表达式，可以反解析到 UI 上
      this.showCron = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSerial(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改串口";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSerial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSerial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除串口编号为"' + ids + '"的数据项？').then(function () {
        return delSerial(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/serial/export', {
        ...this.queryParams
      }, `serial_${new Date().getTime()}.xlsx`)
    },
    /** 分配校验操作 */
    handleAuthDataCheck: function (row) {
      const serialId = row.id;
      this.$router.push("/device/serial-auth-dataCheck/dataCheck/" + serialId);
    },
    handleStatus(row, status) {
      const id = row.id || this.ids
      this.loading = true;
      editGather(id, status).then(response => {
        this.getList();
        var url = this.wsUrl + "/websocket/message/9999";
        ws = new WebSocket(url);
        ws.onopen = function (event) {
          console.log("已经打开连接");
        }
        ws.onmessage = ((event) => {
          var msg = event.data;
          if (msg.includes("vue_msg")) {
            var jsonMsg = JSON.parse(msg);
            this.$message({
              message: jsonMsg["vue_msg"],
              type: 'success'
            });
            if (ws) {
              this.loading = false;
              ws.close();
              ws = null;
            }
          } else {
            console.log(event.data);
          }
        })
        ws.onclose = function (event) {
          console.log("已经关闭连接");
        }
      });
      this.loading = false;
    },
    /** 选择需要下发的命令集合 */
    handleAuthCommand: function (row) {
      const serialId = row.id;
      this.$router.push("/device/serial-choose-command/command/" + serialId);
    },
  }
};
</script>
